<?php
/**
 * 
 * @author tangbl
 *
 */
class CommonAction extends Action {
	
	private $_input ;
	
	/**
     * 初始化
     * 子类重写_initialize方法需要调用parent::_initialize();
     */
	public function _initialize(){
		
		$this->_input = array_merge($_GET,$_POST);
		
		define("APP_ID", $this->_input['app_id']);
		
		//过滤 _sign|_url_ 参数
		$filter = filterRestKey($this->_input);
		
		//检查签名
		//$this->checkSign($filter);
		
		//检查权限
		//$this->checkPermission();
		
	}
	
	/**
	 * 检查签名的过期时间
	 */
	public function checkTimestamp(){
		
		$flag = C("REALTIME_VALIDATE");
		if($flag){
			$nowtime   = time();
			$times     = C("FAILURE_TIME");//5分钟过期
			$timestamp = intval($this->_input["timestamp"]);
			
			if(($nowtime-$timestamp)>$times){
				$this->error(L("cfg_deal_sign_notime"),-2);
			}
		}
	}
	
	/**
	 * 检查应该签名
	 */
	public function checkSign($filter){
	
		$_osign    = $this->_input["_sign"];
		$applist = C("APP_LIST");
		$filter['app_key'] = $applist[APP_ID];
		$_nsign = createRestSign($filter);
		if(empty($_nsign) || $_nsign != $_osign){
			$this->error(L("cfg_deal_sign_nopass"),-5);
		}
		
	}
	
	/**
	 * 检查应用访问权限
	 */
	public function checkPermission(){
		
		$action = ACTION_NAME ;
		$module = MODULE_NAME ;
		
		$appssion = C("APP_PERSSION");
		$perssion = $appssion[APP_ID];
		
		$flag  = false ;
		$flags = $perssion[$module][$action];
		
		if(is_array($flags)){
			$flag = isset($flags['valid']) ? $flags['valid'] : false ;
		}
		
		if(!$flag){
			$this->error(L("cfg_deal_api_forbidden"),-3);
		}
	}
	
	/**
	 * 获取数据权限
	 * @
	 */
	public function getDataAccess(){
		
		$company  = $this->_req("company" , "intval", 0);
		$outletid = $this->_req("outletid", "intval", 0);
		$addid    = $this->_req("addid"   , "intval", 0);
		
		$model    = D("DataAccessView");
		$rows     = $model->find($addid);
		
		$table  = MODULE_NAME ;
		if($rows['outlet'] == 1){
			$map['company'] = $company;
		}elseif($rows['outlet'] == 2){
			$map['company']  = $company;
			$map['outletid'] = $outletid;
		}else{
			$config = C("DATA_ACCESS");
			$array  = $config[$table];
			
			$table  = $array['table'];
			$field  = $array['field'];
			$map[$field]  = $addid;
		}
		return array("table"=>$table,"map"=>$map);
	}
	
	/**
	 * 获取应用参数
	 * @param  int    $company  所属商户
     * @param  int    $outletid 所属门店
     * @param  int    $addid    操作者编号
     * @param  String $addno    操作者工号
	 */
	public function getParams(){
	
		$map['company']  = $this->_req("company" , "intval", 0);
		$map['outletid'] = $this->_req("outletid", "intval", 0);
		$map['addid']    = $this->_req("addid"   , "intval", 0);
		$map['addno']    = $this->_req("addno"   , "trim"  ,"");
	
		return $map;
	}
	
	
	/**
	 * 根据name获取请求的参数
	 * @param String $name    参数名
	 * @param String $fun     过滤函数
	 * @param Object $default 默认值
	 */
	public function _req($name, $fun="", $default){
		
		$val = $this->_input[$name];
		$val = isset($val)?$val:$default;
		
		if(!is_array($val)){
			
			if(empty($fun)){
				$func = C("DEFAULT_FILTER");
			}
			if(function_exists($fun)){
				$val = $fun($val);
			}
		}
		
		return $val;
	}
	
	/**
	 * 返回请求的参数数组
	 */
	public function input(){
		
		return $this->_input;
	}
	
	/**
	 * 成功返回
	 */
	public function success($res,$message='',$type='json'){
		
		$data['status'] = 1;
		$data['data']   = $res;
		$data['info']   = $message;
		$this->response($data,$type);
	}
	
	/**
	 * 错误返回
	 */
	public function error($message,$status="-1",$type='json'){
		
		$data['info']   =   $message;
		$data['status'] =   $status;
		$this->response($data,$type);
		
	}
	
	/**
	 * 分页公共方法
	 * @access private
	 * @param string   $table    表名
	 * @param array    $map      查询条件
	 * @param string   $order    结果排序
	 * @param int      $pageNum  每页数量
	 * @param int      $nowPage  当前页数
	 * @return array
	 */
	public function pageSelect($table,$map,$pageNum,$nowPage,$con){
	
		$model = D("$table");
		
		$count = $model->where($map)->count();
		
		$list  = $model->where($map)->order($con)->page($nowPage.','.$pageNum)->select();
		return array("count"=>$count, "list"=>$list);
	}
	
    
	/**
	 * 公共删除方法
	 * @author tangbl
	 * @param  $table 表名
	 * @param  $param 参数
	 * @param  $flag(true物理删除 false逻辑删除)
	 * $param = array(
	 	"succ"   => '删除成功',//成功提示信息[语言包]
	 	"fail"   => '删除失败',//失败提示信息[语言包]
	 	"after"  => "Article_del_after"//后置方法
	 	"return" => true    //是否需要直接返回
	   );
	 *
	 **/
	protected function do_del($table,$flag=true,$param=array()){
		
		$id = I('param.id',0,'');
		if(!$id) $this->error(L('cfg_form_tipmsg_illgel'));
		
		$group  = GROUP_NAME;
	    $return = isset($param["return"]) ? $param["return"] : true;
		$succ   = isset($param["succ"])   ? $param["succ"]   : "cfg_form_tipmsg_delsucc";
		$fail   = isset($param["fail"])   ? $param["fail"]   : "cfg_form_tipmsg_delfail";
		$after  = @$param["after"];
	
		$model   = M("$table");
		$where   = "id in ($id)";
	
		if($flag){
			$res  = $model->where($where)->delete();
		}else{
			$map["isdel"] = 1 ;
			$res  = $model->where($where)->save($map);
		}
	
		if($res) {			
				
			load("@.".$group);
			//后置操作
			if(function_exists($after)){
				call_user_func($after,$table,$id);
			}
				
			//记录日志
			wapilog();
			if($return){
				$this->success($id,L($succ));
			}else{
				return $id;	
			}
		} else {
			
			wapilog(L($fail));
			if($return){
				$this->error(L($fail));
			}else{
				return false;
			}
		}
	}
	
	/**
	 * 公共修改方法
	 * @author tangbl
	 * @param  $table 表名
	 * @param  $param 参数
	 * $param = array(
		 "upload" => array(
		 	"single"=>array("single"),
		 	"atlas" =>array("atlas"),
		 	"attach"=>array("attach")
		 ), //上传
	 "arr"    => array("title"=>"demo","cateid=1"),//额外字段
	 "after"  => "Article_add_after" //后置方法
	 "before" => "Article_add_before"//前置方法
	 "succ"   => '编辑成功',//成功提示信息[语言包]
	 "return" => true    //是否需要直接返回
	 );
	 **/
	protected function do_edit($table,$param=array()){

		$group  = GROUP_NAME;
		$image  = @$param["upload"];
		$arr    = @$param["arr"];
		$before = @$param["before"];
		$after  = @$param["after"];
		$succ   = isset($param["succ"])   ? $param["succ"]   : "cfg_form_tipmsg_editsucc";
		$return = isset($param["return"]) ? $param["return"] : true;

		$_POST = $this->_input;
		$t     = D("$table");
		
		if($t->create()) {
	
			$solevar = $t->solevar;
			$title   = $t->title;
			$id      = $this->_req("id","intval",0);
		
			if(is_array($arr)){
				foreach($arr as $k=>$v){
					$t->$k=$v;
				}
			}
			
			if(is_array($image)){
					
				$single = @$image['single'];
				if(is_array($single)){
					foreach($single as $v){
						add_edit_thumb($v, $solevar, $table);//添加缩略图
					}
				}
					
				$atlas = @$image['atlas'];
				if(is_array($atlas)){
					foreach($atlas as $v){
						add_edit_album($v, $solevar, $table);//添加图集
					}
				}
					
				$attach = @$image['attach'];
				if(is_array($attach)){
					foreach($attach as $v){
						add_edit_file($v, $solevar, $table);//添加文件
					}
				}
			}
	
			//前置操作
			load("@.".$group);
			if($before && function_exists($before)){
				$t = call_user_func($before,$t,$this);
			}

			$result = $t->save();
	//		echo $t->getLastSql();exit();
	
			//后置操作
			if($after && function_exists($after)){
				call_user_func($after,$table,$id,$this);
			}
			 
			//记录日志
			wapilog();
			if($return){
				$this->success($id,L($succ));
			}else{
				return $id;
			}
		}else{

			//记录日志
			wapilog(L($fail));
			if($return){
				$this->error(L($fail));
			}else{
				return false;
			}
		}
	}
	
	
	/**
	 * 公共添加方法
	 * @author tangbl
	 * @param  $table 表名
	 * @param  $param 参数
	 * $param = array(
		 "upload" => array(
		 	"single"=>array("single"),
		 	"atlas" =>array("atlas"),
		 	"attach"=>array("attach")
		 ), //上传
	 "arr"    => array("title"=>"demo","cateid=1"),//额外字段
	 "after"  => "Article_add_after" //后置方法
	 "before" => "Article_add_before"//前置方法
	 "succ"   => '添加成功',//成功提示信息[语言包]
	 "fail"   => '添加失败',//失败提示信息[语言包]
	 "return" => true    //是否需要直接返回
	 );
	 **/
	protected function do_add($table,$param=array()){
		
		$group  = GROUP_NAME;
		$image  = @$param["upload"];
		
		$arr    = @$param["arr"];
		$before = @$param["before"];
		$after  = @$param["after"];
		$succ   = isset($param["succ"])   ? $param["succ"]   : "cfg_form_tipmsg_addsucc";
		$fail   = isset($param["fail"])   ? $param["fail"]   : "cfg_form_tipmsg_addfail";
		$return = isset($param["return"]) ? $param["return"] : true;
		
		$_POST = $this->_input;
		$t     = D("$table");
		if($t->create()){
			$solevar    = $t->solevar;
			$title      = $t->title;
			$t->lang    = $this->_req("lang" ,"",getLang());
			$t->addid   = $this->_req("addid","intval",0);
			$t->addtime = time();
			
			if(is_array($image)){
			
				$single = @$image['single'];
				if(is_array($single)){
					foreach($single as $v){
						add_edit_thumb($v, $solevar, $table);//添加缩略图
					}
				}
			
				$atlas = @$image['atlas'];
				if(is_array($atlas)){
					foreach($atlas as $v){
						add_edit_album($v, $solevar, $table);//添加图集
					}
				}
			
				$attach = @$image['attach'];
				if(is_array($attach)){
					foreach($attach as $v){
						add_edit_file($v, $solevar, $table);//添加文件
					}
				}
			}
			
			if(is_array($arr)){
				foreach($arr as $k=>$v){
					$t->$k=$v;
				}
			}

			//前置操作
			load("@.".$group);
			if($before && function_exists($before)){
				$t = call_user_func($before,$t,$this);
			}
			
			$result = $t->add();
			
			if($result){
				//后置操作
				if($after && function_exists($after)){
					call_user_func($after,$table,$result,$this);
				}
				//记录日志
				wapilog();
				if($return){
					$this->success($result,L($succ));
				}else{
					return $result;
				}
			}else{
				//记录日志
				wapilog(L($fail));
				if($return){
					$this->error(L($fail));
				}else{
					return false;
				}
			}
		}else{
			//记录日志
			wapilog(L($fail));
			if($return){
				$this->error(L($fail));
			}else{
				return false;
			}
		}
	}
	
	/**
	 * 模板显示 调用内置的模板引擎显示方法，
	 * @param string $charset 输出编码
	 * @param string $contentType 输出类型
	 * @param string $content 输出内容
	 * @param string $prefix 模板缓存前缀
	 * @return void
	 */
	protected function display($templateFile='',$charset='',$contentType='',$content='',$prefix='') {
	
		$depr          = C('TMPL_FILE_DEPR');
		$TMPL_LANG_ARR = C('TMPL_LANG_ARR');
	
		if(empty($templateFile)) {
			// 如果模板文件名为空 按照默认规则定位
			$template = MODULE_NAME . $depr . ACTION_NAME;
		}elseif(strpos('|'.$templateFile,":")){
			$template = str_replace(':', $depr, $templateFile);
		}else{
			$template = MODULE_NAME . $depr .$templateFile;
		}
	
		$lang_file = $TMPL_LANG_ARR[LANG_SET];
		if($lang_file){
			$LANG_PATH = $lang_file.'/';
			$url_suffix = C('TMPL_TEMPLATE_SUFFIX');
			$tpl_file   = TMPL_PATH.$LANG_PATH.$template.$url_suffix;
			 
			if(!file_exists($tpl_file)){
				$lang       = C('DEFAULT_LANG');
				$lang_file  = $TMPL_LANG_ARR[$lang];
			}
			$LANG_PATH = $lang_file.'/';
		}else{
			$LANG_PATH = '/';
		}
	
		$templateFile = $LANG_PATH.$template;
		$this->view->display($templateFile,$charset,$contentType,$content,$prefix);
	}
	
	
	/**
	 *  获取输出页面内容
	 * 调用内置的模板引擎fetch方法，
	 * @access protected
	 * @param string $templateFile 指定要调用的模板文件
	 * 默认为空 由系统自动定位模板文件
	 * @param string $content 模板输出内容
	 * @param string $prefix 模板缓存前缀*
	 * @return string
	 */
	protected function fetch($templateFile='',$content='',$prefix='') {
		
		$depr          = C('TMPL_FILE_DEPR');
		$TMPL_LANG_ARR = C('TMPL_LANG_ARR');
		
		if(empty($templateFile)) {
			// 如果模板文件名为空 按照默认规则定位
			$template = MODULE_NAME . $depr . ACTION_NAME;
		}elseif(strpos('|'.$templateFile,":")){
			$template = str_replace(':', $depr, $templateFile);
		}else{
			$template = MODULE_NAME . $depr .$templateFile;
		}
		
		$lang_file = $TMPL_LANG_ARR[LANG_SET];
		if($lang_file){
			$LANG_PATH = $lang_file.'/';
			$url_suffix = C('TMPL_TEMPLATE_SUFFIX');
			$tpl_file   = TMPL_PATH.$LANG_PATH.$template.$url_suffix;
		
			if(!file_exists($tpl_file)){
				$lang       = C('DEFAULT_LANG');
				$lang_file  = $TMPL_LANG_ARR[$lang];
			}
			$LANG_PATH = $lang_file.'/';
		}else{
			$LANG_PATH = '/';
		}
		$templateFile = $LANG_PATH.$template;
		return $this->view->fetch($templateFile,$content,$prefix);
	}
	
}